package com.lb.statck.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lb.statck.common.result.Result;
import com.lb.statck.config.WechatPayConfig;
import com.lb.statck.pojo.vo.OrderVo;
import com.lb.statck.service.OrderService;
import com.lb.statck.util.QRCodeUtils;
import com.lb.statck.util.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;


import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 @RestController
@RequestMapping("/api/native")
public class nativeController {



    @Value("${spring.weixin.mchId}")
    private String mchId;
    @Autowired
    private WebClient webClient;
    @Autowired
    private WxPayConfig wxPayConfig;

    @Value("${wx.miniapp.wechatPayCertificatePath}")
    private  String wechatPayCertificatePath;
    @Value("${spring.weixin.appid}")
    private String appID;
    @Value("${spring.weixin.appsecret}")
    private String appSecret;
    @Value("${wx.miniapp.merchantId}")
    private String merchantId;
    @Value("${wx.miniapp.privateKeyPath}")
    private String privateKeyPath;
    @Value("${wx.miniapp.merchantSerialNumber}")
    private String merchantSerialNumber;
    @Value("${wx.miniapp.apiV3Key}")
    private String apiV3Key;

    @Value("${wx.miniapp.payNotifyUrl}")
    private String payNotifyUrl;
    @Value("${wx.miniapp.refundNotifyUrl}")
    private String refundNotifyUrl;
    @Value("${wx.miniapp.publicKeyId}")
    private String publicKeyId;
    @Value("${wx.miniapp.publicKeyPath}")
    private String publicKeyPath;
    @Autowired
    private OrderService orderService;


    @PostMapping("/order")
    public Result order(@RequestBody OrderVo orderVo) {
        // 可以根据实际情况使用publicKeyFromPath或publicKey加载公钥
        System.out.println(privateKeyPath);
        Config config =
                new RSAPublicKeyConfig.Builder()
                        .merchantId(merchantId) //微信支付的商户号
                        .privateKeyFromPath(privateKeyPath) // 商户API证书私钥的存放路径
                        .publicKeyFromPath(publicKeyPath) //微信支付公钥的存放路径
                        .publicKeyId(publicKeyId) //微信支付公钥ID
                        .merchantSerialNumber(merchantSerialNumber) //商户API证书序列号
                        .apiV3Key(apiV3Key) //APIv3密钥
                        .build();
      //  QueryWrapper<OrderVo> wrapper=new QueryWrapper();
   //    wrapper.eq("payorderid",orderVo.getPayorderid());
        OrderVo one = orderService.getOnes(orderVo);
        BigDecimal price =   one.getPrice();
        BigInteger bigInteger = price.toBigInteger();
        int i = bigInteger.intValue();
        NativePayService service = new NativePayService.Builder().config(config)
                .build();
        // 预支付请求类
        Amount amount = new Amount();
        amount.setTotal(i);
        PrepayRequest request = new PrepayRequest();
        request.setAmount(amount);
        // 小程序或者公众号的appId
        request.setAppid(appID);
        // 商户号
        request.setMchid(merchantId);
        // 订单描述信息，展示给用户看
        request.setDescription("sss");
        // 回调地址，微信端通知支付结果
        request.setNotifyUrl(payNotifyUrl);
        // 业务端的订单号
        request.setOutTradeNo(orderVo.getPayorderid());
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);

        Map<String,Object> map=new HashMap<>();
        map.put("codeUrl",response.getCodeUrl());
        map.put("order",orderVo.getPayorderid());
Result result=new Result();
result.setData(map);
return result;
    }
    @GetMapping("/qrcode")
    public ResponseEntity<byte[]> generateQRCode(@RequestParam("url") String codeUrl) {
        try {
            int width = 300;
            int height = 300;

            byte[] qrCodeBytes = QRCodeUtils.getQRCodeBytes(codeUrl, width, height);

            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_PNG)
                    .body(qrCodeBytes);
        } catch (Exception e) {
            // 可以记录日志 e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
